package database

import (
	"crypto/md5"
	"fmt"
	"minipromgr/internal/models"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

var DB *gorm.DB

func InitDB() (*gorm.DB, error) {
	return InitDBWithPath("minipromgr.db")
}

func InitDBWithPath(dbPath string) (*gorm.DB, error) {
	var err error
	DB, err = gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
	if err != nil {
		return nil, err
	}
	return DB, nil
}

func InitDefaultData(db *gorm.DB) {
	// 检查是否已有用户数据
	var userCount int64
	db.Model(&models.User{}).Count(&userCount)
	if userCount > 0 {
		return
	}

	// 创建默认用户
	users := []models.User{
		{
			Username: "admin",
			Password: hashPassword("admin123"),
			Name:     "管理员",
			Email:    "admin@example.com",
		},
		{
			Username: "developer",
			Password: hashPassword("dev123"),
			Name:     "开发者",
			Email:    "dev@example.com",
		},
		{
			Username: "tester",
			Password: hashPassword("test123"),
			Name:     "测试员",
			Email:    "test@example.com",
		},
	}

	for _, user := range users {
		db.Create(&user)
	}

	// 创建默认项目
	projects := []models.Project{
		{
			Name:        "Web应用",
			Description: "Web应用程序项目",
		},
		{
			Name:        "移动应用",
			Description: "移动应用程序项目",
		},
		{
			Name:        "API服务",
			Description: "API服务项目",
		},
	}

	for _, project := range projects {
		db.Create(&project)
	}
}

func hashPassword(password string) string {
	hash := md5.Sum([]byte(password))
	return fmt.Sprintf("%x", hash)
}
